import React, { useEffect, useState, useContext } from 'react';
import { Form, Table, Button, Tooltip, Modal, Select, message, Spin, Popconfirm } from 'antd';
import AuthComponent from '@/utils/auth/AuthComponent';
import { withRouter } from 'umi';
import BizIcon from '@/components/BizIcon';

import If from '@/components/If';
import BottomAction from '@/components/BottomAction';
import { isSuccess } from '@/utils/request';
import authHelper from '@/utils/auth/helper';
import { trim } from 'lodash';

import TwoColHead from '@/pages/SalaryManage/components/TwoColHead';
import AutoDivider from '@/pages/SalaryManage/components/AutoDivider';
import {
    goToSkillsDevelopmentTaxInProcess,
    goToSkillsDevelopmentTaxProcessDetail,
    goToSkillsDevelopmentTaxProcessApply
} from '@/pages/SalaryManage/utils/pageNavigateUtil';
import { commonColumn } from '@/pages/SalaryManage/utils/TableUtil';
import { PROCESS_TYPE } from '@/pages/SalaryManage/utils/processUtil';
import { skillsDevelopmentTaxService } from '@/services/salaryManage/salaryCalculateService';
import { getRangeDescription } from '@/pages/SalaryManage/SalaryCalculate/InsuranceFundFile/rangeDescription';
import EmptyPlaceHolder from '@/pages/SalaryManage/components/EmptyPlaceHolder';
import salaryStyle from '@/pages/SalaryManage/salaryManage.less';
import { insuranceFundFileProcessStatus as processStatus } from '@/pages/SalaryManage/enum';
import ProcessStatusTag from '@/pages/SalaryManage/SalaryCalculate/InsuranceFundFile/components/ProcessStatusTag';
import { BaseSettingContext } from '@/pages/SalaryManage/constant/BaseSettingContext';

import pageStyle from './index.less';
import EditDetailModal from './components/editDetailModal';
import { ApproveInfoContext } from './ApproveInfoContext';
import util from './util';

const { Option } = Select;

// 按钮权限
const AUTH_CODE = {
    ADD: 'finance:salary:computation:social:sdl:add',
    EDIT: 'finance:salary:computation:social:sdl:edit',
    DEL: 'finance:salary:computation:social:sdl:delete'
};

// 已生效
const EFFECT_IN = 0;

const SkillsDevelopmentTax = ({ organizationCode, location }) => {
    // 页面表格loading状态
    const [loading, setLoading] = useState(false);
    // 表格数据
    const [sdlListData, setSdlListData] = useState([]);
    // 编辑新增的弹窗展示隐藏状态
    const [visible, setVisible] = useState(false);

    // 重置操作弹出窗的展示/隐藏状态
    const [resetVisible, setResetVisible] = useState(false);
    // 页面数据（是否可重置，是否可下一步，表格id等数据）
    const [pageInitData, setPageInitData] = useState({
        nextAble: false,
        resetAble: false,
        sdlId: ''
    });
    // 审批信息
    const [approveInfo, setApproveInfo] = useState({});
    const { setApproveInfo: setApproveInfoContext } = useContext(ApproveInfoContext);
    const {
        baseSetting: { scale = 2 }
    } = useContext(BaseSettingContext);

    // 用于判断待生效已生效的界面不同的展示
    const effect = location?.query?.effect ? +location?.query?.effect : EFFECT_IN;
    // 待编辑的数据
    const [editData] = useState({
        data: null
    });

    const getSdlList = () => {
        setLoading(true);
        // 入参 effect: 档案生效状态,0 查询当前档案,   1查询待生效档案
        const params = {
            effect,
            organizationCode
        };
        skillsDevelopmentTaxService
            .querySdlList(params)
            .then(res => {
                if (isSuccess(res)) {
                    setPageInitData(res?.data || {});
                    setSdlListData(res?.data?.rows || []);
                }
                setLoading(false);
            })
            .catch(() => {
                setLoading(false);
            });
    };

    const tableColumn = operateConfig => {
        const rel = [
            {
                title: '雇员该自然月薪资总额(X)',
                dataIndex: 'monthAmount',
                align: 'left',
                render: (text, record) => {
                    const { twStartAmt, twStartAmtSign, twEndAmt, twEndAmtSign } =
                        record || {};
                    const str = getRangeDescription(util.getNumberFormat(twStartAmt, false, scale), twStartAmtSign, util.getNumberFormat(twEndAmt, false, scale), twEndAmtSign, '$');
                    return <EmptyPlaceHolder value={str}></EmptyPlaceHolder>;
                }
            },
            commonColumn({
                title: '雇主扣除额',
                dataIndex: 'amount',
                align: 'left',
                width: 280,
                render: (text, record) => {
                    const { sdlAmt = 0, sdlRate = 0, sdlPayStyle = '' } = record || {};
                    const str = sdlPayStyle === 2 ? `月薪资总额 ${util.getNumberFormat(sdlRate, true, scale)}%` : `$${util.getNumberFormat(sdlAmt, false, scale) ?? 0}`;
                    return <span>{str}</span>;
                }
            })
        ];
        if (operateConfig) {
            const { onEdit, onDelete, disabled } = operateConfig;

            rel.push({
                title: '操作',
                dataIndex: 'v_operate',
                width: 100,
                fixed: 'right',
                render(text, record) {
                    return (
                        <AutoDivider>
                            <If condition={authHelper.checkCode(AUTH_CODE.EDIT)}>
                                <Tooltip title="编辑" >
                                    <Button
                                        className={salaryStyle.operateIcon}
                                        onClick={() => onEdit(record)}
                                        disabled={disabled}
                                    >
                                        <BizIcon type="listfunction_edit_icon_default" />
                                    </Button>
                                </Tooltip>
                            </If>
                            <If condition={authHelper.checkCode(AUTH_CODE.DEL)}>
                                <Popconfirm
                                    title="确定要删除吗？"
                                    onConfirm={() => onDelete(record)}
                                    disabled={disabled}
                                >
                                    <Tooltip title="删除" >
                                        <Button className={salaryStyle.operateIcon} disabled={disabled}>
                                            <BizIcon type="DeleteIcon" />
                                        </Button>
                                    </Tooltip>
                                </Popconfirm>
                            </If>
                        </AutoDivider>
                    );
                }
            });
        }

        return rel;
    };
    const onEdit = record => {
        editData.data = record;
        editData.data.sdlId = pageInitData.sdlId;
        setVisible(true);
    };
    const onDelete = record => {
        setLoading(true);
        skillsDevelopmentTaxService
            .queryDeleSdl({ id: record.id, sdlId: pageInitData.sdlId })
            .then(response => {
                if (isSuccess(response)) {
                    message.success('删除成功');
                    getSdlList();
                } else {
                    message.error(response.msg);
                }
                setLoading(false);
            })
            .catch(() => {
                setLoading(false);
            });
    };
    const saveEdit = params => {
        // 保存编辑
        setLoading(true);
        const newObj = params;
        Object.keys(params).forEach(item => {
            if (!trim(params[item])) delete newObj[item];
        });
        const savePromise = editData?.data?.id
            ? skillsDevelopmentTaxService.querySdlDetail(newObj)
            : skillsDevelopmentTaxService.querySettingSdl(newObj);

        savePromise
            .then(saveResponse => {
                setLoading(false);
                if (isSuccess(saveResponse)) {
                    message.success(editData?.data?.id ? '编辑成功' : '新增成功');
                    setVisible(false);
                    getSdlList();
                } else {
                    message.error(saveResponse.msg);
                }
            })
            .finally(() => {
                setLoading(false);
                setVisible(false);
            });
    };
    const reset = () => {
        setResetVisible(true);
    };
    const doReset = () => {
        setLoading(true);
        skillsDevelopmentTaxService
            .queryResetSdl({ sdlId: pageInitData.sdlId })
            .then(response => {
                if (!isSuccess(response)) {
                    message.warn(response.msg);
                    return;
                }
                setResetVisible(false);
                message.success('重置成功！');
                getSdlList();
            })
            .finally(() => {
                setLoading(false);
            });
    };
    const onNext = async () => {
        // 获取查询条件
        setLoading(true);
        try {
            const response = await skillsDevelopmentTaxService.querySdlCheck({
                sdlId: pageInitData.sdlId
            });
            setLoading(false);
            if (!isSuccess(response)) {
                message.warn(response.msg);
                return;
            }
        } catch (e) {
            setLoading(false);
        }
        await goToSkillsDevelopmentTaxProcessApply(
            PROCESS_TYPE.SALARY_SET_SDL_APPLY,
            { organizationCode, socialId: pageInitData.sdlId, sdlId: pageInitData.sdlId },
            '没有找到分类为【财务险金档案流程】的流程，请先配置流程'
        );
    };

    useEffect(() => {
        if (organizationCode) {
            getSdlList();
        }
    }, [organizationCode]);

    useEffect(() => {
        if (pageInitData?.sdlId) {
            skillsDevelopmentTaxService
                .querySdlApproveDetail({
                    sdlId: pageInitData?.sdlId
                })
                .then(response => {
                    if (isSuccess(response)) {
                        setApproveInfo(response.data);
                        if (EFFECT_IN !== effect) {
                            // 设置流程信息，【待生效档案】有用到
                            setApproveInfoContext(response.data);
                        }
                    }
                });
        }
    }, [pageInitData]);

    return (
        <Spin spinning={loading}>
            <TwoColHead
                left={
                    <Form layout="inline">
                        <span style={{ marginLeft: '8px' }}>
                            <Select style={{ width: '208px' }} defaultValue="全体员工" allowClear={false} disabled>
                                <Option value="全体员工">全体员工</Option>
                            </Select>
                        </span>
                        <If condition={EFFECT_IN === effect}>
                            <span style={{ marginLeft: '8px' }}>
                                <Button
                                    type="primary"
                                    ghost
                                    onClick={() => goToSkillsDevelopmentTaxInProcess(organizationCode)}
                                >
                                    待生效档案
                                </Button>
                            </span>
                        </If>

                        <span style={{ marginLeft: '8px' }}>
                            <Button
                                type="primary"
                                ghost
                                onClick={() =>
                                    goToSkillsDevelopmentTaxProcessDetail({
                                        processDefinitionId: approveInfo?.processDefinitionId,
                                        processInstanceId: approveInfo?.processId
                                    })
                                }
                                disabled={!(approveInfo.processDefinitionId && approveInfo.processId)}
                            >
                                查看审批详情
                            </Button>
                        </span>
                    </Form>
                }
                right={
                    EFFECT_IN === effect ? (
                        <AuthComponent code={AUTH_CODE.ADD}>
                            <Button
                                type="primary"
                                style={{ width: '88px' }}
                                onClick={() => {
                                    editData.data = null;
                                    setVisible(true);
                                }}
                                disabled={processStatus?.APPROVING === pageInitData?.processStatus}
                            >
                                新增
                            </Button>
                        </AuthComponent>
                    ) : null
                }
            />
            <div className={pageStyle.tableBox}>
                <header className={pageStyle.h1}>
                    <span>技能发展税维护表</span>
                    <ProcessStatusTag
                        status={pageInitData?.processStatus}
                        style={{ marginLeft: '8px', marginBottom: '2px' }}
                    />
                </header>

                <Table
                    bordered
                    rowKey="id"
                    columns={tableColumn(
                        EFFECT_IN === effect
                            ? {
                                onEdit,
                                onDelete,
                                disabled: processStatus.APPROVING === pageInitData?.processStatus
                            }
                            : null,
                        scale
                    )}
                    loading={loading}
                    dataSource={sdlListData}
                    pagination={false}
                />
            </div>
            <div
                style={{
                    height: '83px',
                    backgroundColor: '#FAFAFA',
                    paddingTop: '16px',
                    paddingLeft: '16px',
                    marginTop: '16px'
                }}
            >
                <div style={{ color: 'rgba(0, 0, 0, 0.85)', fontSize: '14px', fontWeight: 'bold' }}>备注：</div>
                <div style={{ color: 'rgba(0, 0, 0, 0.65)', fontSize: '14px', marginTop: '7px' }}>
                    月薪总额是指任何薪金、工资、佣金、奖金、假期工资、加班费、津贴（包括住房或其他类似津贴）和其他现金支付
                </div>
            </div>

            <If condition={visible && EFFECT_IN === effect}>
                <EditDetailModal
                    visible={visible}
                    onCancel={() => setVisible(false)}
                    editData={editData.data ? editData.data : {}}
                    editRowId={editData?.data?.id || ''}
                    onlyUpdate={editData?.data?.id}
                    title={editData?.data?.id ? '编辑' : '新增'}
                    onOk={saveEdit}
                    sdlId={pageInitData.sdlId}
                />
            </If>
            <If condition={EFFECT_IN === effect}>
                <BottomAction>
                    <Button onClick={reset} disabled={!pageInitData.resetAble}>
                        重置
                    </Button>
                    <Button type="primary" onClick={onNext} disabled={!pageInitData.nextAble}>
                        下一步
                    </Button>
                    <Modal
                        visible={resetVisible}
                        title="重置"
                        okText="确定"
                        cancelText="取消"
                        onOk={doReset}
                        onCancel={() => setResetVisible(false)}
                        width={480}
                        centered
                    >
                        <div style={{ margin: '30px 20px' }}>
                            重置后所有数据将回退到上次审批通过的结果，是否确定重置？
                        </div>
                    </Modal>
                </BottomAction>
            </If>
        </Spin>
    );
};

export default withRouter(SkillsDevelopmentTax);
